package com.xdf.ecommerce.filter;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.concurrent.TimeUnit;

/**
 * 全局过滤器，记录请求耗时，单位：毫秒
 * @author chanchaw
 * @create 2025-10-18 9:54
 */
@Slf4j
@Component
public class GlobalElapsedLogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Stopwatch sw = Stopwatch.createStarted();
        String path = exchange.getRequest().getURI().getPath();
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    log.info("请求:[{}],耗时:[{}ms]",path,sw.elapsed(TimeUnit.MILLISECONDS));
                })
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
